package com.naiterui.ehp.bs.doctor.dao.impl;

import com.naiterui.ehp.bp.domain.PatientRecord;
import com.naiterui.ehp.bp.domain.PatientRecordImg;
import com.naiterui.ehp.bs.doctor.dao.IPatientRecordImgDao;
import com.naiterui.ehp.bs.doctor.repository.IPatientRecordImgRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 患者诊疗记录图片持久层实现
 *
 * @author Amber
 * @since 1.0.0
 */
@Repository
public class AdPatientRecordImgDaoImpl implements IPatientRecordImgDao {

    @Autowired
    private IPatientRecordImgRepository patientRecordImgRepository;

    @Override
    public void saveOrUpdate(PatientRecordImg recordImg)
    {
        if(recordImg.getId() == null){
            patientRecordImgRepository.save(recordImg);
        } else{
            patientRecordImgRepository.update(recordImg);
        }
    }

    @Override
    public Map<Long, List<PatientRecordImg>> getRecordImgs(List<PatientRecord> result) {
        // 返回结果
        Map<Long, List<PatientRecordImg>> mapResult = new HashMap<>();
        // 目标数组为空直接返回
        if (result == null || result.isEmpty()) {
            return mapResult;
        }

        // 目标诊疗记录id数组
        List<Long> recordIds = new ArrayList<>();
        for (PatientRecord record : result) {
            recordIds.add(record.getId());
        }

        // 查询诊疗记录相关图片
        List<PatientRecordImg> imgs = patientRecordImgRepository.findByRecordIdIn(recordIds);

        // 查询结果按诊疗记录分组
        for (PatientRecordImg img : imgs) {
            List<PatientRecordImg> imgsByRecord = mapResult.get(img.getRecordId());
            if (imgsByRecord == null) {
                imgsByRecord = new ArrayList<>();
                mapResult.put(img.getRecordId(), imgsByRecord);
            }
            imgsByRecord.add(img);
        }

        return mapResult;
    }

    /**
     * 查询医生指定的图片资源
     * IPatientRecordImgDao.findPatientRecordImg()
     *
     * @return
     *
     * @Author YongYang
     * @Date 2017年6月10日
     * @since 1.0.0
     */
    @Override
    public List<PatientRecordImg> findPatientRecordImg(String recordUuid, String picIds) {
        List<String> uuidList = new ArrayList<>();
        if (picIds != null && !"".equals(picIds)) {
            String[] uuids = picIds.split(",");
            for (String uuid : uuids) {
                uuidList.add(uuid);
            }
        }

        return patientRecordImgRepository.findByRecordUuidAndUuidIn(recordUuid, uuidList);
    }

    /**
     * 删除图片资源
     * IPatientRecordImgDao.delete()
     *
     * @param patientRecordImg
     *
     * @Author YongYang
     * @Date 2017年6月10日
     * @since 1.0.0
     */
    @Override
    public void delete(PatientRecordImg patientRecordImg) {
        patientRecordImgRepository.delete(patientRecordImg);
    }
}
